package com.hw.one.transpot.util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.hw.one.collect.config.DropTimeConfig;
import com.hw.one.collect.entity.CommonData;
import com.hw.one.transpot.constant.DeviceCodeConstant;
import com.hw.one.transpot.entity.TCPDataTransporter;

/**
 * @Class TransporteDataHandler
 * @Author guoshenzhen
 * @Date 2018/4/3 18:43
 */
public class TransporteDataHandler extends ChannelInboundHandlerAdapter {
	private Logger log = Logger.getLogger(this.getClass());
	private final LinkedList<CommonData> data;
	CommonData now = null;
	TCPDataTransporter p = new TCPDataTransporter();
	
	public TransporteDataHandler(LinkedList<CommonData> msg) {
		this.data = msg;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		if (data.size() > 0) {
			now = data.pop();
			String json = p.toJSON(now);
			log.debug("开始发送------------>>>>>>>" + json);
			ctx.writeAndFlush(json + "\\q");
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		JSONObject o = JSONObject.parseObject(msg.toString());
		if (o.getString("code").equals("111")) {
			// 更新传输成功时间
			DropTimeConfig.putDropTime(now.getDeviceCode() + ":" + now.getTime());
			if (data.size() > 0) {
				
				now = data.pop();
				String json = p.toJSON(now);
				
				log.debug("开始发送------------>>>>>>>" + json);
				ctx.writeAndFlush(json + "\\q");
			} else if (data.size() == 0) {
				this.channelInactive(ctx);
				ctx.close();
			}
		}
	}
}
